import { withPixiApp, Container } from '@inlet/react-pixi'
import React from 'react'
import { connect } from 'react-redux'
import { Case, SwitchCase } from 'components/switch'
import { projectLabelView as projectDuck } from 'ducks'
import PropTypes from 'prop-types'
import Polygon from './polygon'
import Rectangle from './rectangle'
import Keypoint from './keypoint'
import Check from './checkmark'

const EditPointView = ({ scale, classes, editLabel }) => {
  let minXandY
  if (editLabel) {
    minXandY = editLabel.exterior.reduce((pre, next, i) => {
      if (i === 0) {
        pre.minx = next[0]
        pre.miny = next[1]
      } else {
        pre.minx = next[0] < pre.minx ? next[0] : pre.minx
        pre.miny = next[1] < pre.miny ? next[1] : pre.miny
      }
      return pre
    }, {})
  }

  return (
    <Container>
      {editLabel && (
        <SwitchCase switchValue={classes[editLabel.class_id].type}>
          <Case value="rectangle" render={() => <Rectangle label={editLabel} scale={scale} />} />
          <Case value="polygon" render={() => <Polygon label={editLabel} scale={scale} />} />
          <Case value="keypoint" render={() => <Keypoint label={editLabel} scale={scale} />} />
        </SwitchCase>
      )}
      {editLabel && <Check x={minXandY.minx} y={minXandY.miny} scale={scale} />}
    </Container>
  )
}

EditPointView.propTypes = {
  scale: PropTypes.number.isRequired,
  classes: PropTypes.object.isRequired,
  editLabel: PropTypes.object,
}

EditPointView.defaultProps = {
  editLabel: undefined,
}

const mapStateToProps = state => ({
  classes: projectDuck.selectors.classes(state),
  editLabel: projectDuck.selectors.editLabel(state),
})

export default withPixiApp(connect(mapStateToProps)(EditPointView))
